﻿#NoEnv
#MaxMem 2048
#NoTrayIcon
#SingleInstance, Off
#MaxThreadsPerHotkey 100
#MaxHotkeysPerInterval 400
#Persistent
#WinActivateForce
#Include %A_ScriptDir%
Process, Priority,, High
#include lib/Class_GdipAll.ahk
#include lib/class_yaml.ahk
#Include lib/Class_ImageButton.ahk
CoordMode, ToolTip, Screen
;;DetectHiddenWindows, On
OnMessage(0x200, "WM_MOUSEMOVE")

Menu, TRAY, NoStandard
Menu, TRAY, DeleteAll
RegRead, WeaselRoot, HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Rime\Weasel, WeaselRoot
RegRead, InstallDir, HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Rime\Weasel, InstallDir
RegRead, RimeUserDir, HKEY_CURRENT_USER\Software\Rime\Weasel, RimeUserDir
RimeUserDir:=RimeUserDir?RimeUserDir:A_AppData "\Rime",Theme_Color:={}, marks:=""""
Theme_Color:={author: "佛振 <chen.sst@gmail.com>, based on ir_black",name: "暗堂／Dark Temple",back_color: "0x222222",border_color: "0x222222",candidate_text_color: "0xd8e3e6",comment_text_color: "0x606cff",hilited_back_color: "0x222222",hilited_candidate_back_color: "0x333333",hilited_candidate_text_color: "0x92f6da",hilited_text_color: "0xffcf9a",text_color: "0x92f6da",label_color: "0xd8e3e6"}
Select_Color_Mode:=0,Default_theme_name:="dark_temple"
Color_template=
(
"preset_color_schemes/example":
    author:
    name:
    border_color:
    back_color:
    hilited_back_color:
    hilited_candidate_back_color:
    text_color:
    hilited_candidate_text_color:
    hilited_text_color:
    candidate_text_color:
    comment_text_color:
    label_color:
)
Color_template:=RegExReplace(Color_template,"`r","`n"),Color_template:=RegExReplace(Color_template,"`n","`r`n")
Color_template:=A_Space A_Space RegExReplace(Color_template,"(?<=preset\_color\_schemes\/)\w+",Default_theme_name)
for key,value In ["name","author","border_color","back_color","hilited_back_color","hilited_candidate_back_color","text_color","hilited_candidate_text_color","hilited_text_color","candidate_text_color","comment_text_color","label_color"]
{
	Color_template:=RegExReplace(Color_template,"(?<=\s" value "\:)[^\r\n]*",A_space (Theme_Color[value]~="i)0x[\w]+"?Theme_Color[value]:"""" Theme_Color[value] """"))
}


if !WeaselRoot
{
	if !A_IconHidden 
		TrayTip, Weasel,  此设置没有安装Rime!,,3
	theme_all:=[Default_theme_name]:=Theme_Color
}Else{
	WeaselObj:=yaml(RimeUserDir "\build\weasel.yaml",1,"UTF-8")
	theme_all:=WeaselObj["preset_color_schemes"]
}

If !A_IsAdmin {
	Try
	{
		If A_IsCompiled {
			Run *RunAs "%A_ScriptFullPath%" /restart
			ExitApp
		}else{
			Run *RunAs "%A_AhkPath%" /restart "%A_ScriptFullPath%"
		}
	}
	Catch
	{
		MsgBox, 262160,, 以管理员身份运行失败！,8
		ExitApp
	}
}

If A_IsCompiled {
	thisPID := DllCall("GetCurrentProcessId")
	if objCount(Processlist:=GetProcessNameList(A_ScriptName))>1
	{
		loop,% objCount(Processlist)
		{
			if (thisPID<>Processlist[A_Index,2]){
				process,Close,% Processlist[A_Index,2]
			}
		}
	}
}Else{
	DetectHiddenWindows, On
	thisPID := DllCall("GetCurrentProcessId")
	WinGet, List, List, %A_ScriptFullPath% ahk_class AutoHotkey
	Loop % List
	{ 
		WinGet, PID, PID, % "ahk_id" List%A_Index%
		If (PID != thisPID){
			Process, Close, %PID%
		}
	}
	DetectHiddenWindows, Off
}

DllCall("Shell32\SHChangeNotify", Int,0x8000000, UInt,0, Ptr,0, Ptr,0)
if FileExist(WeaselRoot "\WeaselServer.exe"){
	Process,Exist,WeaselServer.exe
	if !ErrorLevel
		Run *RunAs "%WeaselRoot%\WeaselServer.exe" /restart
}
Gosub themeColorGui

FormatColor_1(Color){
	if (strlen(Color)=8&&InStr(Color,0x)){
		Return "#" SubStr(Color,7,2) SubStr(Color,5,2) SubStr(Color,3,2)
	}else if (strlen(Color)=6&&!InStr(Color,0x)){
		Return "#" SubStr(Color,5,2) SubStr(Color,3,2) SubStr(Color,1,2)
	}
}

WM_MOUSEMOVE(){
	global Theme_Color
	static CurRControl, PrevControl
	Tip_Show:={back_color: "候选框背景底色" FormatColor_1(Theme_Color["back_color"])
		,border_color: "边框颜色，与底色相同则为无边框的效果`r`nborder_color：`r`n`tHex：" FormatColor_1(Theme_Color["border_color"])
		,text_color: "编码行文字颜色`r`ntext_color：`r`n`tHex：" FormatColor_1(Theme_Color["text_color"]) 
		,hilited_text_color: "高亮文字，即与当前高亮候选 对应的那部份输入码`r`nhilited_text_color：`r`n`tHex：" FormatColor_1(Theme_Color["hilited_text_color"])
		,hilited_back_color: "设定高亮文字的底色，可起到凸显高亮部份的作用`r`nhilited_back_color：`r`n`tHex：" FormatColor_1(Theme_Color["hilited_back_color"])
		,hilited_candidate_text_color: "高亮候选项的文字颜色`r`nhilited_candidate_text_color：`r`n`tHex：" FormatColor_1(Theme_Color["hilited_candidate_text_color"])
		,hilited_candidate_back_color: "高亮候选项的底色`r`nhilited_candidate_back_color：`r`n`tHex：" FormatColor_1(Theme_Color["hilited_candidate_back_color"])
		,candidate_text_color: "候选项文字颜色`r`ncandidate_text_color：`r`n`tHex：" FormatColor_1(Theme_Color["candidate_text_color"]),ToNextGui:"切换到窗口状态管理窗口"
		,comment_text_color: "提示选项字体颜色`r`ncomment_text_color：`r`n`tHex：" FormatColor_1(Theme_Color["comment_text_color"]),import_theme:"转换为yaml单行格式并复制到剪切板"
		,label_color: "候选项序号标签字体颜色`r`nlabel_color：`r`n`tHex：" FormatColor_1(Theme_Color["label_color"]),get_custom_color:"鼠标自动取色，LCtrl键终止取色"}
	CurRControl := InStr(A_GuiControl,"get_custom_color")?"get_custom_color":A_GuiControl
	if (CurRControl <> PrevControl and not InStr(CurRControl, " "))
	{
		SetTimer, DisplayToolTip, 500
		PrevControl := CurRControl
	}

	DisplayToolTip:
		SetTimer, DisplayToolTip, Off
		ToolTip % Tip_Show[CurRControl]
		SetTimer, RMToolTip, 3000
	return

	RMToolTip:
		SetTimer, RMToolTip, Off
		ToolTip
	return
}

~LCtrl::
	Goto Select_Color_end
Return

themeColorGui:
	Gui, themeColors:destroy
	Gui, themeColors: -MaximizeBox +LastFound %parentOwner% hwnddiytheme
	Gui,themeColors: Add, Pic,w130 h210 vbordercolor, % "HBITMAP:" . CreateColoredBitmap(130, 210, FormatColor(Theme_Color["border_color"]))
	Gui,themeColors: Add, Pic,xp+3 yp+3 w124 h204 vbackcolor, % "HBITMAP:" . CreateColoredBitmap(124, 204, FormatColor(Theme_Color["back_color"]))
	Gui,themeColors:font,s10 bold
	Gui,themeColors: Add, text,% "xp+5 yp+10 BackgroundTrans vtextcolor c" SubStr(FormatColor(Theme_Color["text_color"]),3),小狼毫
	Gui,themeColors: Add, Pic,x+8 yp-1 w42 h18 vhilited_backcolor, % "HBITMAP:" . CreateColoredBitmap(94, 194, FormatColor(Theme_Color["hilited_back_color"]))
	Gui,themeColors: Add, text,% "xp+2 yp BackgroundTrans vhilited_textcolor c" SubStr(FormatColor(Theme_Color["hilited_text_color"]),3),peis
	Gui,themeColors: Add, Pic,xm+8 y+20 w114 h20 vhilited_candidate_backcolor, % "HBITMAP:" . CreateColoredBitmap(90, 18, FormatColor(Theme_Color["hilited_candidate_back_color"]))
	Gui,themeColors: Add, text,% "xp+2 yp+2 BackgroundTrans vhilited_candidate_textcolor c" SubStr(FormatColor(Theme_Color["hilited_candidate_text_color"]),3),1.配送〔sgud〕

	Theme_Color["label_color"]:=Theme_Color["label_color"]?Theme_Color["label_color"]:Theme_Color["candidate_text_color"]
	Gui,themeColors: Add, text,% "xp y+12 BackgroundTrans vlabel_color1 c" SubStr(FormatColor(Theme_Color["label_color"]),3),2.
	Gui,themeColors: Add, text,% "x+0 yp BackgroundTrans vcandidate_textcolor1 c" SubStr(FormatColor(Theme_Color["candidate_text_color"]),3),配色
	Gui,themeColors: Add, text,% "x+3 yp BackgroundTrans vcomment_textcolor1 c" SubStr(FormatColor(Theme_Color["comment_text_color"]),3),〔sgqc〕

	Gui,themeColors: Add, text,% "xm+10 y+12 BackgroundTrans vlabel_color2 c" SubStr(FormatColor(Theme_Color["label_color"]),3),3.
	Gui,themeColors: Add, text,% "x+0 yp BackgroundTrans vcandidate_textcolor2 c" SubStr(FormatColor(Theme_Color["candidate_text_color"]),3),配饰
	Gui,themeColors: Add, text,% "x+3 yp BackgroundTrans vcomment_textcolor2 c" SubStr(FormatColor(Theme_Color["comment_text_color"]),3),〔sgqn〕

	Gui,themeColors: Add, text,% "xm+10 y+12 BackgroundTrans vlabel_color3 c" SubStr(FormatColor(Theme_Color["label_color"]),3),4.
	Gui,themeColors: Add, text,% "x+0 yp BackgroundTrans vcandidate_textcolor3 c" SubStr(FormatColor(Theme_Color["candidate_text_color"]),3),配售
	Gui,themeColors: Add, text,% "x+3 yp BackgroundTrans vcomment_textcolor3 c" SubStr(FormatColor(Theme_Color["comment_text_color"]),3),〔sgwy〕

	Gui,themeColors: Add, text,% "xm+10 y+12 BackgroundTrans vlabel_color4 c" SubStr(FormatColor(Theme_Color["label_color"]),3),5.
	Gui,themeColors: Add, text,% "x+0 yp BackgroundTrans vcandidate_textcolor4 c" SubStr(FormatColor(Theme_Color["candidate_text_color"]),3),配上
	Gui,themeColors: Add, text,% "x+3 yp BackgroundTrans vcomment_textcolor4 c" SubStr(FormatColor(Theme_Color["comment_text_color"]),3),〔sghh〕

	Gui,themeColors: Add, text,% "xm+10 y+12 BackgroundTrans vlabel_color5 c" SubStr(FormatColor(Theme_Color["label_color"]),3),6.
	Gui,themeColors: Add, text,% "x+0 yp BackgroundTrans vcandidate_textcolor5 c" SubStr(FormatColor(Theme_Color["candidate_text_color"]),3),赔上
	Gui,themeColors: Add, text,% "x+3 yp BackgroundTrans vcomment_textcolor5 c" SubStr(FormatColor(Theme_Color["comment_text_color"]),3),〔muhh〕
	Gui,themeColors:font,s10 norm
	Gui,themeColors: Add, edit,xm y225 w130 gShowthemestyle vsetthemeName hWndthemeName,
	EM_SetCueBanner(themeName, objCount(Theme_Color)?"主题名：dark_temple":"主题名称")
	Gui,themeColors: Add, edit,xm y+8 w130 gShowthemestyle vsetthemeInfo hWndthemeInfo,
	EM_SetCueBanner(themeInfo, Theme_Color["name"]?"简介：" Theme_Color["name"]:"主题介绍")
	Gui,themeColors: Add, edit,xm y+8 w130 gShowthemestyle vsetthemeAuthor hWndthemeAuthor,
	EM_SetCueBanner(themeAuthor, Theme_Color["author"]?"作者：" Theme_Color["author"]:"作者")

	Gui,themeColors: Add, button,x160 y5 gset_color vback_color hwndback_color,% Theme_Color["back_color"]
	Gui,themeColors: Add, button,xp y+8 gset_color vborder_color hwndborder_color,% Theme_Color["border_color"]
	Gui,themeColors: Add, button,xp y+8 gset_color vtext_color hwndtext_color,% Theme_Color["text_color"]
	Gui,themeColors: Add, button,xp y+8 gset_color vhilited_text_color hwndhilited_text_color,% Theme_Color["hilited_text_color"]
	Gui,themeColors: Add, button,xp y+8 gset_color vhilited_back_color hwndhilited_back_color,% Theme_Color["hilited_back_color"]
	Gui,themeColors: Add, button,xp y+8 gset_color vhilited_candidate_text_color hwndhilited_candidate_text_color,% Theme_Color["hilited_candidate_text_color"]
	Gui,themeColors: Add, button,xp y+8 gset_color vhilited_candidate_back_color hwndhilited_candidate_back_color,% Theme_Color["hilited_candidate_back_color"]
	Gui,themeColors: Add, button,xp y+8 gset_color vcandidate_text_color hwndcandidate_text_color,% Theme_Color["candidate_text_color"]
	Gui,themeColors: Add, button,xp y+8 gset_color vcomment_text_color hwndcomment_text_color,% Theme_Color["comment_text_color"]
	Gui,themeColors: Add, button,xp y+8 gset_color vlabel_color hwndlabel_color,% Theme_Color["label_color"]
	Gui,themeColors: Add, button,x+10 ym gget_custom_color vget_custom_color1 HWNDBTNC1,鼠标取色
	ImageButton.Create(BTNC1, [6, 0x80404040, 0x222222, 0xffffff], [ , 0x80606060, 0xF0F0F0, 0x111111],"", [0, 0xC0A0A0A0, , 0xC0e81010])
	Loop,9
	{
		Index:=A_Index+1,BTNControl=BTNC%Index%
		Gui,themeColors: Add, button,xp y+8 gget_custom_color vget_custom_color%Index% HWNDBTNC%Index%,鼠标取色
	}
	GuiControlGet,ThemePos1,themeColors:Pos,get_custom_color1
	GuiControlGet,ThemePos10,themeColors:Pos,get_custom_color10
	ThemePosH:=ThemePos10Y-ThemePos1Y+ThemePos10H,ThemePosX:=ThemePos10X+ThemePos10W+15
	Gui,themeColors: Add, Text,x%ThemePosX% ym h%ThemePosH% 0x11
	Gui,themeColors: Add, edit,% "x+10 ym w400 h" ThemePosH " ReadOnly gShowthemestyle vShowthemestyle -E0x200", %Color_template%   ; -HScroll
	ImageButton.Create(BTNC2, [6, 0x80404040, 0x222222, 0xffffff], [ , 0x80606060, 0xF0F0F0, 0x111111],"", [0, 0xC0A0A0A0, , 0xC0e81010])
	ImageButton.Create(BTNC3, [6, 0x80404040, 0x222222, 0xffffff], [ , 0x80606060, 0xF0F0F0, 0x111111],"", [0, 0xC0A0A0A0, , 0xC0e81010])
	ImageButton.Create(BTNC4, [6, 0x80404040, 0x222222, 0xffffff], [ , 0x80606060, 0xF0F0F0, 0x111111],"", [0, 0xC0A0A0A0, , 0xC0e81010])
	ImageButton.Create(BTNC5, [6, 0x80404040, 0x222222, 0xffffff], [ , 0x80606060, 0xF0F0F0, 0x111111],"", [0, 0xC0A0A0A0, , 0xC0e81010])
	ImageButton.Create(BTNC6, [6, 0x80404040, 0x222222, 0xffffff], [ , 0x80606060, 0xF0F0F0, 0x111111],"", [0, 0xC0A0A0A0, , 0xC0e81010])
	ImageButton.Create(BTNC7, [6, 0x80404040, 0x222222, 0xffffff], [ , 0x80606060, 0xF0F0F0, 0x111111],"", [0, 0xC0A0A0A0, , 0xC0e81010])
	ImageButton.Create(BTNC8, [6, 0x80404040, 0x222222, 0xffffff], [ , 0x80606060, 0xF0F0F0, 0x111111],"", [0, 0xC0A0A0A0, , 0xC0e81010])
	ImageButton.Create(BTNC9, [6, 0x80404040, 0x222222, 0xffffff], [ , 0x80606060, 0xF0F0F0, 0x111111],"", [0, 0xC0A0A0A0, , 0xC0e81010])
	ImageButton.Create(BTNC10, [6, 0x80404040, 0x222222, 0xffffff], [ , 0x80606060, 0xF0F0F0, 0x111111],"", [0, 0xC0A0A0A0, , 0xC0e81010])
	Gui,themeColors: Add, Text,xm y+15 w720 h2 0x10 vTextLine1
	for key,value in theme_all
		outthemelist.=value["Name"] "|"
	Gui,themeColors: Add, text,xm y+15, 用户主题
	Gui,themeColors: Add, DropDownList,x+5 yp w180 vcustomthemelist gcustomthemelist hwndcustomthemelist, % outthemelist
	GuiControl,themeColors:ChooseString,customthemelist,% theme_all[Default_theme_name,"name"]
	Gui,themeColors: Add, button,x+15 yp gsave_theme vsave_theme HWNDBTNT2,保存
	ImageButton.Create(BTNT2, [6, 0x80404040, 0x222222, 0xffffff], [ , 0x80606060, 0xF0F0F0, 0x111111],"", [0, 0xC0A0A0A0, , 0xC0e81010])
	Gui,themeColors: Add, button,x+15 yp gimport_theme vimport_theme HWNDBTNT4,复制为单行格式
	ImageButton.Create(BTNT4, [6, 0x80404040, 0x222222, 0xffffff], [ , 0x80606060, 0xF0F0F0, 0x111111],"", [0, 0xC0A0A0A0, , 0xC0e81010])
	GuiControlGet,themestylePos,themeColors:Pos,TextLine1
	GuistylePosX:=themestylePosX+themestylePosW-ThemePos1W*1.65,GuistylePosY:=themestylePosY+themestylePosH+10

	Gui,themeColors: Add, button,x%GuistylePosX% y%GuistylePosY% gToNextGui vToNextGui HWNDBTNT3,切换至进程管理
	ImageButton.Create(BTNT3, [6, 0x80404040, 0x222222, 0xffffff], [ , 0x80606060, 0xF0F0F0, 0x111111],"", [0, 0xC0A0A0A0, , 0xC0e81010])
	For key,value In Theme_Color
	{
		SetButtonColor(key,FormatColor(value))
	}
	Gui, themeColors:Add, StatusBar,,
	Gui, themeColors:Color, FFFFFF
	Gui,themeColors:show,AutoSize,小狼毫主题配置
	ChangeWindowIcon("Shell32.dll", WinExist("ahk_id " diytheme), 81)
	EmptyMem()
Return

Select_Color_end:
	if Select_Color_Mode {
		Select_Color_Mode:=!Select_Color_Mode
		SetTimer, WatchCursor, Off
		GuiControl,themeColors:,%active_label%,鼠标取色
		Switch Index
		{
			Case 1:
				ImageButton.Create(BTNC1, [6, 0x80404040, 0x222222, 0xffffff], [ , 0x80606060, 0xF0F0F0, 0x111111],"", [0, 0xC0A0A0A0, , 0xC0e81010])
			Case 2:
				ImageButton.Create(BTNC2, [6, 0x80404040, 0x222222, 0xffffff], [ , 0x80606060, 0xF0F0F0, 0x111111],"", [0, 0xC0A0A0A0, , 0xC0e81010])
			Case 3:
				ImageButton.Create(BTNC3, [6, 0x80404040, 0x222222, 0xffffff], [ , 0x80606060, 0xF0F0F0, 0x111111],"", [0, 0xC0A0A0A0, , 0xC0e81010])
			Case 4:
				ImageButton.Create(BTNC4, [6, 0x80404040, 0x222222, 0xffffff], [ , 0x80606060, 0xF0F0F0, 0x111111],"", [0, 0xC0A0A0A0, , 0xC0e81010])
			Case 5:
				ImageButton.Create(BTNC5, [6, 0x80404040, 0x222222, 0xffffff], [ , 0x80606060, 0xF0F0F0, 0x111111],"", [0, 0xC0A0A0A0, , 0xC0e81010])
			Case 6:
				ImageButton.Create(BTNC6, [6, 0x80404040, 0x222222, 0xffffff], [ , 0x80606060, 0xF0F0F0, 0x111111],"", [0, 0xC0A0A0A0, , 0xC0e81010])
			Case 7:
				ImageButton.Create(BTNC7, [6, 0x80404040, 0x222222, 0xffffff], [ , 0x80606060, 0xF0F0F0, 0x111111],"", [0, 0xC0A0A0A0, , 0xC0e81010])
			Case 8:
				ImageButton.Create(BTNC8, [6, 0x80404040, 0x222222, 0xffffff], [ , 0x80606060, 0xF0F0F0, 0x111111],"", [0, 0xC0A0A0A0, , 0xC0e81010])
			Case 9:
				ImageButton.Create(BTNC9, [6, 0x80404040, 0x222222, 0xffffff], [ , 0x80606060, 0xF0F0F0, 0x111111],"", [0, 0xC0A0A0A0, , 0xC0e81010])
			Case 10:
				ImageButton.Create(BTNC10, [6, 0x80404040, 0x222222, 0xffffff], [ , 0x80606060, 0xF0F0F0, 0x111111],"", [0, 0xC0A0A0A0, , 0xC0e81010])
		}
		GuiControl,themeColors:,%active_label%,鼠标取色
		if CursorColor~="i)^0x[0-9a-fA-F]{5,6}$"
			Theme_Color[button_label]:=FormatColor(CursorColor)
	}
Return

get_custom_color:
	get_button_list:=["back_color","border_color","text_color","hilited_text_color","hilited_back_color","hilited_candidate_text_color","hilited_candidate_back_color","candidate_text_color","comment_text_color","label_color"]
	if button_label:= get_button_list[Index:=RegExReplace(A_GuiControl,"[^\d]")]{
		Select_Color_Mode:=1,active_label:=A_GuiControl
		GuiControl,themeColors:,%active_label%,LCtrl终止
		Switch Index
		{
			Case 1:
				ImageButton.Create(BTNC1, [6, 0x80404040, 0xe81010, 0xffffff], [ , 0x80606060, 0x15c23c, 0xffffff],"", [0, 0xC0A0A0A0, , 0xC0e81010])
			Case 2:
				ImageButton.Create(BTNC2, [6, 0x80404040, 0xe81010, 0xffffff], [ , 0x80606060, 0x15c23c, 0xffffff],"", [0, 0xC0A0A0A0, , 0xC0e81010])
			Case 3:
				ImageButton.Create(BTNC3, [6, 0x80404040, 0xe81010, 0xffffff], [ , 0x80606060, 0x15c23c, 0xffffff],"", [0, 0xC0A0A0A0, , 0xC0e81010])
			Case 4:
				ImageButton.Create(BTNC4, [6, 0x80404040, 0xe81010, 0xffffff], [ , 0x80606060, 0x15c23c, 0xffffff],"", [0, 0xC0A0A0A0, , 0xC0e81010])
			Case 5:
				ImageButton.Create(BTNC5, [6, 0x80404040, 0xe81010, 0xffffff], [ , 0x80606060, 0x15c23c, 0xffffff],"", [0, 0xC0A0A0A0, , 0xC0e81010])
			Case 6:
				ImageButton.Create(BTNC6, [6, 0x80404040, 0xe81010, 0xffffff], [ , 0x80606060, 0x15c23c, 0xffffff],"", [0, 0xC0A0A0A0, , 0xC0e81010])
			Case 7:
				ImageButton.Create(BTNC7, [6, 0x80404040, 0xe81010, 0xffffff], [ , 0x80606060, 0x15c23c, 0xffffff],"", [0, 0xC0A0A0A0, , 0xC0e81010])
			Case 8:
				ImageButton.Create(BTNC8, [6, 0x80404040, 0xe81010, 0xffffff], [ , 0x80606060, 0x15c23c, 0xffffff],"", [0, 0xC0A0A0A0, , 0xC0e81010])
			Case 9:
				ImageButton.Create(BTNC9, [6, 0x80404040, 0xe81010, 0xffffff], [ , 0x80606060, 0x15c23c, 0xffffff],"", [0, 0xC0A0A0A0, , 0xC0e81010])
			Case 10:
				ImageButton.Create(BTNC10, [6, 0x80404040, 0xe81010, 0xffffff], [ , 0x80606060, 0x15c23c, 0xffffff],"", [0, 0xC0A0A0A0, , 0xC0e81010])
		}
		GuiControl,themeColors:,%active_label%,LCtrl终止
		SetTimer, WatchCursor, 100
	}
Return

WatchCursor:
	GetCursorPos(xpos, ypos)
	WinSet, AlwaysOnTop, On , ahk_id %diytheme%
	WinActivate,
	CursorColor:=GetCursorColor(xpos,ypos)
	if CursorColor~="i)^0x[0-9a-fA-F]{5,6}$"{
		CursorColor:=StrLen(CursorColor)<8?RegExReplace(CursorColor,"i)0x","0x0"):CursorColor
		if (CursorColor_last<>CursorColor){
			CursorColor_last:=CursorColor
			SetButtonColor(button_label,StringLower(CursorColor))
			GuiControl,themeColors:, %button_label%, % StringLower(FormatColor(CursorColor))
			Color_template:=InStr(Color_template,A_Space button_label ":")?RegExReplace(Color_template,"(?<=\s" button_label "\:)[^\r\n]*",A_Space StringLower(FormatColor(CursorColor))):Color_template (Color_template~="\n$"?"    ":"`r`n    ") button_label ": " StringLower(FormatColor(CursorColor))
			GuiControl,themeColors:,Showthemestyle,% Color_template
			If (button_label ="border_color"){
				GuiControl,themeColors:, bordercolor,% "HBITMAP:" . CreateColoredBitmap(130, 210,CursorColor)
			}else If (button_label="back_color"){
				GuiControl,themeColors:, backcolor,% "HBITMAP:" . CreateColoredBitmap(124, 204,CursorColor)
			}else If (button_label="hilited_back_color"){
				GuiControl,themeColors:, hilited_backcolor,% "HBITMAP:" . CreateColoredBitmap(94, 194,CursorColor)
			}else If (button_label="hilited_candidate_back_color"){
				GuiControl,themeColors:, hilited_candidate_backcolor,% "HBITMAP:" . CreateColoredBitmap(90,18,CursorColor)
			}else If (button_label="text_color"){
				Gui,themeColors:font, % "s10 bold c" SubStr(CursorColor,3)
				GuiControl, themeColors:Font, textcolor
			}else If (button_label="hilited_candidate_text_color"){
				Gui,themeColors:font, % "s10 bold c" SubStr(CursorColor,3)
				GuiControl, themeColors:Font, hilited_candidate_textcolor
			}else If (button_label="hilited_text_color"){
				Gui,themeColors:font, % "s10 bold c" SubStr(CursorColor,3)
				GuiControl, themeColors:Font, hilited_textcolor
			}else If (button_label="candidate_text_color"){
				Gui,themeColors:font, % "s10 bold c" SubStr(CursorColor,3)
				loop,5
					GuiControl, themeColors:Font, candidate_textcolor%A_Index%
			}else If (button_label="comment_text_color"){
				Gui,themeColors:font, % "s10 bold c" SubStr(CursorColor,3)
				loop,5
					GuiControl, themeColors:Font, comment_textcolor%A_Index%
			}else If (button_label="label_color"){
				Gui,themeColors:font, % "s10 bold c" SubStr(CursorColor,3)
				loop,5
					GuiControl, themeColors:Font, label_color%A_Index%
			}
		}
	}
return

set_color:
	If Dlg_Color(tempColor, diytheme){
		SetButtonColor(%A_GuiControl%,"0x" SubStr(tempColor,3)),Theme_Color[A_GuiControl]:=FormatColor(tempColor)
		GuiControl,themeColors:, %A_GuiControl%, % FormatColor(tempColor)
		GuiControl,themeColors:,Showthemestyle,% Color_template:=RegExReplace(Color_template,"(?<=\s" A_GuiControl "\:)[^\r\n]*",A_Space Theme_Color[A_GuiControl] )
		If (A_GuiControl ="border_color")
			GuiControl,themeColors:, bordercolor,% "HBITMAP:" . CreateColoredBitmap(130, 210,tempColor)
		else If (A_GuiControl="back_color")
			GuiControl,themeColors:, backcolor,% "HBITMAP:" . CreateColoredBitmap(124, 204,tempColor)
		else If (A_GuiControl="hilited_back_color")
			GuiControl,themeColors:, hilited_backcolor,% "HBITMAP:" . CreateColoredBitmap(94, 194,tempColor)
		else If (A_GuiControl="hilited_candidate_back_color")
			GuiControl,themeColors:, hilited_candidate_backcolor,% "HBITMAP:" . CreateColoredBitmap(90,18,tempColor)
		else If (A_GuiControl="text_color"){
			Gui,themeColors:font, % "s10 bold c" SubStr(tempColor,3)
			GuiControl, themeColors:Font, textcolor
		}else If (A_GuiControl="hilited_candidate_text_color"){
			Gui,themeColors:font, % "s10 bold c" SubStr(tempColor,3)
			GuiControl, themeColors:Font, hilited_candidate_textcolor
		}else If (A_GuiControl="hilited_text_color"){
			Gui,themeColors:font, % "s10 bold c" SubStr(tempColor,3)
			GuiControl, themeColors:Font, hilited_textcolor
		}else If (A_GuiControl="candidate_text_color"){
			Gui,themeColors:font, % "s10 bold c" SubStr(tempColor,3)
			loop,5
				GuiControl, themeColors:Font, candidate_textcolor%A_Index%
		}else If (A_GuiControl="comment_text_color"){
			Gui,themeColors:font, % "s10 bold c" SubStr(tempColor,3)
			loop,5
				GuiControl, themeColors:Font, comment_textcolor%A_Index%
		}else If (A_GuiControl="label_color"){
			Gui,themeColors:font, % "s10 bold c" SubStr(tempColor,3)
			loop,5
				GuiControl, themeColors:Font, label_color%A_Index%
		}
	}
Return

themeColorsGuiClose:
	EmptyMem()
	ExitApp
Return

import_theme:
	GuiControlGet,thisColor,,Showthemestyle,text
	if thisColor {
		Clipboard:=thisColor
		ClipWait,0
		if !A_IconHidden 
			TrayTip,WeaselTool,已复制到剪切板！,,1
		Else{
			SB_SetText("  已复制到剪切板！")
			Sleep,3500
			SB_SetText("")
		}
	}
/*
	thisColor:=""
	if objCount(Theme_Color){
		for key,value In Theme_Color
		{
			if key in border_color,back_color,hilited_back_color,hilited_candidate_back_color,text_color,hilited_candidate_text_color,hilited_text_color,candidate_text_color,comment_text_color,label_color
			{
				if Not value~="^(0x|0X)"
					value:=StrLen(Format("0x{:x}", value))<8?Format("0x0{:x}", value):Format("0x{:x}", value)
			}
			if value~="i)^0x[0-9A-Fa-f]{5,8}"
				thisColor.=A_Space key ": " value ","
			Else
				thisColor.=A_Space key ": " """" value """"  ","
		}
	}
	if thisColor {
		thisColor:= A_Space A_Space """" "preset_color_schemes/" Default_theme_name """" ": {" RegExReplace(thisColor,"\,$") "}"
		Clipboard:=thisColor
		TrayTip,WeaselTool,已复制到剪切板！,,1
	}
*/
Return

ToNextGui:
	Gui,themeColors:Cancel
	Gosub Select_Color_end
	DetectHiddenWindows, On
	if WinExist("ahk_id " AsciiModeGui)
		Gui,Ascii_mode:Show,Center
	else
		Gosub Ascii_mode_Gui
	DetectHiddenWindows, Off
Return

Showthemestyle:
	GuiControlGet,GetEditText,,%A_GuiControl%,text
	if GetEditText {
		if (A_GuiControl="setthemeName"){
			If GetEditText~="^[a-z0-9\_]+$" {
				GuiControl,themeColors:,Showthemestyle,% RegExReplace(Color_template,"(?<=preset\_color\_schemes\/)\w+",GetEditText)
			}else{
				Gui +OwnDialogs
				MsgBox , 262192, , 配色参数名仅支持「英文､数字、下划线」组合！,5
				GuiControl,themeColors:,%A_GuiControl%,
			}
		}else if (A_GuiControl="setthemeInfo"){
			GuiControl,themeColors:,Showthemestyle,% Color_template:=RegExReplace(Color_template,"(?<=\sname\:)[^\r\n]+",A_Space """" GetEditText """")
		}else if (A_GuiControl="setthemeAuthor"){
			GuiControl,themeColors:,Showthemestyle,% Color_template:=RegExReplace(Color_template,"(?<=\sauthor\:)[^\r\n]+",A_Space """" GetEditText """")
		}
	}Else{
		if (A_GuiControl="setthemeName"){
			GuiControl,themeColors:,Showthemestyle,% Color_template:=RegExReplace(Color_template,"(?<=preset\_color\_schemes\/)\w+",Default_theme_name)
		}else if (A_GuiControl="setthemeInfo"){
			GuiControl,themeColors:,Showthemestyle,% Color_template:=RegExReplace(Color_template,"(?<=\sname\:)[^\r\n]+","""" Theme_Color["name"] """")
		}else if (A_GuiControl="setthemeAuthor"){
			GuiControl,themeColors:,Showthemestyle,% Color_template:=RegExReplace(Color_template,"(?<=\sauthor\:)[^\r\n]+","""" Theme_Color["author"] """")
		}
	}
Return

getDefauleTheme(obj,themeName){
	for key,value in obj
		if (value["name"]==themeName)
			Return key
	Return ""
}

save_theme:
	FileAppend,********************************************`r`n%Color_template%`r`n********************************************`r`n`r`n,%A_Desktop%\Weasel.txt,UTF-8
	OpenAndSelect(A_Desktop "\Weasel.txt")
Return

customthemelist:
	If A_GuiControl {
		GuiControlGet, customthemename,, customthemelist, text
		If customthemename {
			If themeID:=getDefauleTheme(theme_all,customthemename) {
				Default_theme_name:=themeID,Theme_Color:=theme_all[Default_theme_name]
				Theme_Color["label_color"]:=Theme_Color["label_color"]?Theme_Color["label_color"]:Theme_Color["candidate_text_color"]
				for key,value in ["border_color","back_color","hilited_back_color","hilited_candidate_back_color","text_color","hilited_candidate_text_color","hilited_text_color","candidate_text_color","comment_text_color","label_color"]
				{
					SetButtonColor(value,StringLower(FormatColor(Theme_Color[value])))
					GuiControl,themeColors:, %value%, % StringLower(Theme_Color[value])
					If (value ="border_color")
						GuiControl,themeColors:, bordercolor,% "HBITMAP:" . CreateColoredBitmap(130, 210,FormatColor(Theme_Color[value]))
					else If (value="back_color")
						GuiControl,themeColors:, backcolor,% "HBITMAP:" . CreateColoredBitmap(124, 204,FormatColor(Theme_Color[value]))
					else If (value="hilited_back_color")
						GuiControl,themeColors:, hilited_backcolor,% "HBITMAP:" . CreateColoredBitmap(94, 194,FormatColor(Theme_Color[value]))
					else If (value="hilited_candidate_back_color")
						GuiControl,themeColors:, hilited_candidate_backcolor,% "HBITMAP:" . CreateColoredBitmap(90,18,FormatColor(Theme_Color[value]))
					else If (value="text_color"){
						Gui,themeColors:font, % "s10 bold c" SubStr(FormatColor(Theme_Color[value]),3)
						GuiControl, themeColors:Font, textcolor
					}else If (value="hilited_candidate_text_color"){
						Gui,themeColors:font, % "s10 bold c" SubStr(FormatColor(Theme_Color[value]),3)
						GuiControl, themeColors:Font, hilited_candidate_textcolor
					}else If (value="hilited_text_color"){
						Gui,themeColors:font, % "s10 bold c" SubStr(FormatColor(Theme_Color[value]),3)
						GuiControl, themeColors:Font, hilited_textcolor
					}else If (value="candidate_text_color"){
						Gui,themeColors:font, % "s10 bold c" SubStr(FormatColor(Theme_Color[value]),3)
						loop,5
							GuiControl, themeColors:Font, candidate_textcolor%A_Index%
					}else If (value="comment_text_color"){
						Gui,themeColors:font, % "s10 bold c" SubStr(FormatColor(Theme_Color[value]),3)
						loop,5
							GuiControl, themeColors:Font, comment_textcolor%A_Index%
					}else If (value="label_color"){
						Gui,themeColors:font, % "s10 bold c" SubStr(FormatColor(Theme_Color[value]),3)
						loop,5
							GuiControl, themeColors:Font, label_color%A_Index%
					}
				}
				GuiControl, themeColors:, setthemeInfo,% Theme_Color["name"]
				GuiControl, themeColors:, setthemeAuthor,% Theme_Color["author"]
				GuiControl, themeColors:, setthemeName,% Default_theme_name
				thisColor:=""
				if objCount(Theme_Color){
					for key,value In Theme_Color
					{
						if key in border_color,back_color,hilited_back_color,hilited_candidate_back_color,text_color,hilited_candidate_text_color,hilited_text_color,candidate_text_color,comment_text_color,label_color
						{
							if Not value~="^(0x|0X)"
								value:=StrLen(Format("0x{:x}", value))<8?Format("0x0{:x}", value):Format("0x{:x}", value)
						}
						if value~="i)^0x[0-9A-Fa-f]{5,8}"
							thisColor.=A_Space A_Space A_Space A_Space key ": " value "`r`n"
						Else
							thisColor.=A_Space A_Space A_Space A_Space key ": " """" value """"  "`r`n"
					}
				}
				if thisColor {
					thisColor:= A_Space A_Space """" "preset_color_schemes/" Default_theme_name """" ":`r`n" thisColor
					GuiControl,themeColors:,Showthemestyle,% Color_template:=thisColor
				}
			}
		}
	}
Return

Ascii_mode_Gui:
	Gui,Ascii_mode:Destroy
	Gui,Ascii_mode:Default
	Gui, Ascii_mode: +LastFound hwndAsciiModeGui
	Gui,Ascii_mode:Font,s10 norm
	Gui,Ascii_mode:Add,ListView,r10 w450 AltSubmit Grid -LV0x10 -Multi Checked NoSortHdr -WantF2 0x8 LV0x40 gSetProcessStates,进程名|输入状态|进程描述
	Yaml:=Yaml(RimeUserDir "\build\weasel.yaml",1,"UTF-8"),States:=Yaml["app_options"]
	SysGet, CXVSCROLL, 2
	For section,element In States
	{
		Process, Exist , %section%
		LV_Add("", section , element["ascii_mode"]="true"?"英文":"中文",ErrorLevel?FileGetInfo(GetProcessInfo(Section),"FileDescription"):"")
	}
	LV_ModifyCol(1,150),LV_ModifyCol(2,100 " center"),LV_ModifyCol(3,200-CXVSCROLL*(A_ScreenDPI/96) " center")
	Gui,Ascii_mode:Add,Button, HWNDToLast gToLastGui,切换到配色
	Gui,Ascii_mode:Add,Button,x+15 yp HWNDadd_Process gadd_Process vadd_Process,添加进程
	Gui,Ascii_mode:Add,Button,x+15 yp HWNDdelete_Process gdelete_Process vdelete_Process,删除
	Gui,Ascii_mode:Add,Button,x+15 yp HWNDReload_Process gReload_Process,重载
	GuiControl,Ascii_mode:Disable,delete_Process
	Gui,Ascii_mode:Add,Button,x+15 yp HWNDExportResult gExportResult ,导出列表
	Gui,Ascii_mode:Add,Button,x+15 yp HWNDCopyResult gCopyResult ,复制列表
	ImageButton.Create(ToLast, [6, 0x80404040, 0x222222, 0xffffff], [ , 0x80606060, 0xF0F0F0, 0x111111],"", [0, 0xC0A0A0A0, , 0xC0e81010])
	ImageButton.Create(add_Process, [6, 0x80404040, 0x222222, 0xffffff], [ , 0x80606060, 0xF0F0F0, 0x111111],"", [0, 0xC0A0A0A0, , 0xC0e81010])
	ImageButton.Create(ExportResult, [6, 0x80404040, 0x222222, 0xffffff], [ , 0x80606060, 0xF0F0F0, 0x111111],"", [0, 0xC0A0A0A0, , 0xC0e81010])
	ImageButton.Create(CopyResult, [6, 0x80404040, 0x222222, 0xffffff], [ , 0x80606060, 0xF0F0F0, 0x111111],"", [0, 0xC0A0A0A0, , 0xC0e81010])
	ImageButton.Create(delete_Process, [6, 0x80404040, 0x222222, 0xffffff], [ , 0x80606060, 0xF0F0F0, 0x111111],"", [0, 0xC0A0A0A0, , 0xC0e81010])
	ImageButton.Create(Reload_Process, [6, 0x80404040, 0x222222, 0xffffff], [ , 0x80606060, 0xF0F0F0, 0x111111],"", [0, 0xC0A0A0A0, , 0xC0e81010])
	Gui,Ascii_mode:Add,StatusBar,,% "  双击行切换状态！"
	Gui,Ascii_mode:Show,AutoSize,小狼毫窗口状态管理
	ChangeWindowIcon("Shell32.dll", WinExist("ahk_id " AsciiModeGui), 166)
Return

ToLastGui:
	EmptyMem()
	Gui,Ascii_mode:Cancel
	Gui,themeColors:Show,Center
Return

Ascii_modeGuiClose:
	EmptyMem()
	ExitApp
Return

Reload_Process:
	LV_Delete()
	Yaml:=Yaml(RimeUserDir "\build\weasel.yaml",1,"UTF-8"),States:=Yaml["app_options"]
	For section,element In States
	{
		Process, Exist , %section%
		LV_Add("", section , element["ascii_mode"]="true"?"英文":"中文",ErrorLevel?FileGetInfo(GetProcessInfo(Section),"FileDescription"):"")
	}
	LV_ModifyCol(1,150),LV_ModifyCol(2,100 " center"),LV_ModifyCol(3,200-CXVSCROLL*(A_ScreenDPI/96) " center")
Return

delete_Process:
	Loop % (LV_GetCount(),a:=1)
	{
		if ( LV_GetNext( 0, "C" ) = a ){
			LV_GetText(LVName1, a , 1),LV_Delete( a )
			ObjDelete(States, LVName1)
		}else
			++a
	}
Return

SetProcessStates:
	if (A_GuiEvent="Normal") {
		LV_GetText(LVName2,A_EventInfo,2),LV_GetText(LVName1,A_EventInfo,1), LVPOS:= A_EventInfo
		loop, % LV_GetCount()+1
		{
			if LV_GetNext( A_Index-1, "Checked" ){
				GuiControl,Ascii_mode:Enable,delete_Process
				break
			}else{
				GuiControl,Ascii_mode:Disable,delete_Process
				break
			}
		}
	}else if (A_GuiEvent="DoubleClick") {
		LV_GetText(LVName2,A_EventInfo,2),LV_GetText(LVName1,A_EventInfo,1), LVPOS:= A_EventInfo
		LV_Modify(A_EventInfo,"text",LVName1,LVName2="英文"?"中文":"英文"),States[LVName1,"ascii_mode"]:=States[LVName1,"ascii_mode"]="false"?"true":"false"
	}
Return

ExportResult:
	if objCount(States){
		Gui,+OwnDialogs
		MsgBox, 262724, 备份提示, 是否导出列表？
		IfMsgBox, Yes
		{
			result:=""
			for key,value in States
			{
				result.=("  app_options/" StringLower(key) ": {ascii_mode: " value["Ascii_mode"] "}`r`n")
			}
			if result {
				FileAppend,********************************************`r`n%result%`r`n********************************************`r`n`r`n,%A_Desktop%\Weasel.txt,UTF-8
				OpenAndSelect(A_Desktop "\Weasel.txt")
			}
		}
	}
Return

add_Process:
	SB_SetText("<<< 鼠标选择目标活动窗口LCtrl键添加，限时10秒！>>>")
	GuiControl,Ascii_mode:,add_Process,LCtrl确认
	ImageButton.Create(add_Process, [6, 0x80404040, 0xe81010, 0xffffff], [ , 0x80606060, 0x15c23c, 0xffffff],"", [0, 0xC0A0A0A0, , 0xC0e81010])
	GuiControl,Ascii_mode:,add_Process,LCtrl确认
	keywait, LCtrl, D T10
	keywait, LCtrl
	MouseGetPos, , , id
	WinGet, win_exe, ProcessName, ahk_id %id%,
	If !objCount(States[win_exe]) {
		LV_Add("",StringLower(win_exe),"中文",FileGetInfo(GetProcessInfo(win_exe),"FileDescription"))
		States[StringLower(win_exe),"ascii_mode"]:="false"
	}
	GuiControl,Ascii_mode:,add_Process,添加进程
	ImageButton.Create(add_Process, [6, 0x80404040, 0x222222, 0xffffff], [ , 0x80606060, 0xF0F0F0, 0x111111],"", [0, 0xC0A0A0A0, , 0xC0e81010])
	GuiControl,Ascii_mode:,add_Process,添加进程
	SB_SetText("  双击行切换状态！")
Return

CopyResult:
	if objCount(States){
		result:=""
		for key,value in States
		{
			result.=("  app_options/" StringLower(key) ": {ascii_mode: " value["Ascii_mode"] "}`r`n")
		}
		if result {
			Clipboard:=result
			ClipWait,0
			if !A_IconHidden 
				TrayTip,WeaselTool,结果已复制到剪切板！,,1
			else{
				SB_SetText("  结果已复制到剪切板！")
				Sleep,3500
				SB_SetText("  双击行切换状态！")
			}
		}
	}
Return

SetButtonColor(ControlID, Color,HWND_:="themeColors", Margins:=3){
	GuiControlGet, hwnd, %HWND_%:Hwnd, %ControlID%
	VarSetCapacity(RECT, 16, 0), DllCall("User32.dll\GetClientRect", "Ptr", hwnd, "Ptr", &RECT)
	W := NumGet(RECT, 8, "Int") - (Margins * 1.5), H := NumGet(RECT, 12, "Int") - (Margins * 1.5)
	Color:=((Color&0xFF)<<16)+(Color&0xFF00)+((Color>>16)&0xFF)
	hbm:=CreateDIBSection(W, H), hdc := CreateCompatibleDC(), obm := SelectObject(hdc, hbm)
	hBrush:=DllCall("CreateSolidBrush", "UInt", Color, "UPtr"), obh:=SelectObject(hdc, hBrush)
	DllCall("Rectangle", "UPtr", hdc, "Int", 0, "Int", 0, "Int", W, "Int", H), SelectObject(hdc, obm)
	BUTTON_IMAGELIST_ALIGN_CENTER := 4, BS_BITMAP := 0x0080, BCM_SETIMAGELIST := 0x1602, BITSPIXEL := 0xC
	BPP := DllCall("Gdi32.dll\GetDeviceCaps", "Ptr", hdc, "Int", BITSPIXEL)
	HIL := DllCall("Comctl32.dll\ImageList_Create", "UInt", W, "UInt", H, "UInt", BPP, "Int", 6, "Int", 0, "Ptr")
	DllCall("Comctl32.dll\ImageList_Add", "Ptr", HIL, "Ptr", hbm, "Ptr", 0)
	; ; Create a BUTTON_IMAGELIST structure
	VarSetCapacity(BIL, 20 + A_PtrSize, 0), NumPut(HIL, BIL, 0, "Ptr")
	Numput(BUTTON_IMAGELIST_ALIGN_CENTER, BIL, A_PtrSize + 16, "UInt")
	SendMessage, BCM_SETIMAGELIST, 0, 0, , ahk_id %HWND%
	SendMessage, BCM_SETIMAGELIST, 0, &BIL, , ahk_id %HWND%
	SelectObject(hdc, obh), DeleteObject(hbm), DeleteObject(hBrush), DeleteDC(hdc)
}

FormatColor(Color){
	if (strlen(Color)=8&&InStr(Color,0x)){
		Return SubStr(Color,1,2) SubStr(Color,7,2) SubStr(Color,5,2) SubStr(Color,3,2)
	}else if (strlen(Color)=6&&!InStr(Color,0x)){
		Return SubStr(Color,5,2) SubStr(Color,3,2) SubStr(Color,1,2)
	}
}

CreateColoredBitmap(width, height, color) {
	hBitmap := CreateDIBSections(width, -height,, pBits)
	Loop % height {
		i := A_Index - 1
		Loop % width
			NumPut(color, pBits + width*4*i + (A_Index - 1)*4, "UInt")
	}
	Return hBitmap
}

CreateDIBSections(w, h, bpp := 32, ByRef ppvBits := 0)
{
	hdc := DllCall("GetDC", "Ptr", 0, "Ptr")
	VarSetCapacity(bi, 40, 0)
	NumPut( 40, bi,  0, "UInt")
	NumPut(  w, bi,  4, "UInt")
	NumPut(  h, bi,  8, "UInt")
	NumPut(  1, bi, 12, "UShort")
	NumPut(  0, bi, 16, "UInt")
	NumPut(bpp, bi, 14, "UShort")
	hbm := DllCall("CreateDIBSection", "Ptr", hdc, "Ptr", &bi, "UInt", 0, "PtrP", ppvBits, "Ptr", 0, "UInt", 0, "Ptr")
	DllCall("ReleaseDC", "Ptr", 0, "Ptr", hdc)
	return hbm
}

EM_SetCueBanner(hWnd, Cue)
{
	static EM_SETCUEBANNER := 0x1501
	return DllCall("User32.dll\SendMessage", "Ptr", hWnd, "UInt", EM_SETCUEBANNER, "Ptr", True, "WStr", Cue)
}

GetDefaultFontName(){
	NumPut(VarSetCapacity(info, A_IsUnicode ? 504 : 344, 0), info, 0, "UInt")
	DllCall("SystemParametersInfo", "UInt", 0x29, "UInt", 0, "Ptr", &info, "UInt", 0)
	return StrGet(&info + 52)
}

GetFileContent(FilePath,Encoding="UTF-8"){
	If FileExist(FilePath){
		FileEncoding,%Encoding%
		FileRead,chars,%FilePath%
		chars:=RegExReplace(RegExReplace(RegExReplace(chars,"`r`n","`r"),"`n","`r"),"`r","`r`n")
		return RegExReplace(chars,"`r`n[\s\t]+`r`n","`r`n")
	}
}

;-----------------------------------------配色----------------------------------------------------------
/*!
	函数: Dlg_Color(ByRef r_Color, hOwner:=0, Palette*)---->显示用于选择颜色的标准窗口对话框。

	参数:
		r_Color - 初始颜色-->默认设置为黑色.
		hOwner - 对话框对象的窗口ID, 如果有的话默认为0, i.e. 没有对象. 如果指定的DlgX和DlgY被忽略.
		Palette -最多16个RGB颜色值的数组。这些将成为对话框中的初始自定义颜色。
	Remarks:
		对话框中的自定义颜色在调用时被标记。如果用户选择OK，则将加载调色板阵列（如果存在）使用对话框中的自定义颜色。
	Returns:
		如果用户选择“确定”，返回True。否则返回False
*/
Dlg_Color(ByRef r_Color, hOwner:=0, Palette*){
	Static CHOOSECOLOR, A_CustomColors
	if !VarSetCapacity(A_CustomColors){
		If !objCount(Palette)
			Palette:= [0x1C7399,0xEEEEEC,0x014E8B,0x444444,0x009FE8,0xDEF9FA,0xF8B62D,0x90FC0F,0x0078D7,0x0D1B0A,0xB9D497,0x00ADEF,0x1778BF,0xFDF6E3,0x002B36,0xDEDEDE]
		VarSetCapacity(A_CustomColors,64,0)
		for Index, Value in Palette
			NumPut(Value, A_CustomColors, 4*(Index - 1), "UInt")
	}
	l_Color:=r_Color, l_Color:=((l_Color&0xFF)<<16)+(l_Color&0xFF00)+((l_Color>>16)&0xFF)
	;-- 创建并填充CHOOSECOLOR结构
	lStructSize:=VarSetCapacity(CHOOSECOLOR,(A_PtrSize=8) ? 72:36,0)
	NumPut(lStructSize,CHOOSECOLOR,0,"UInt")            ;-- lStructSize
	NumPut(hOwner,CHOOSECOLOR,(A_PtrSize=8) ? 8:4,"Ptr")
	;-- hwndOwner
	NumPut(l_Color,CHOOSECOLOR,(A_PtrSize=8) ? 24:12,"UInt")
	;-- RGB结果
	NumPut(&A_CustomColors,CHOOSECOLOR,(A_PtrSize=8) ? 32:16,"Ptr")
	;-- lpCustColors
	NumPut(0x00000103,CHOOSECOLOR,(A_PtrSize=8) ? 40:20,"UInt")
	;-- Flags
	RC:=DllCall("comdlg32\ChooseColor" . (A_IsUnicode ? "W":"A"),"Ptr",&CHOOSECOLOR)
	;-- 按下“取消”按钮或关闭对话框
	if (RC=0)
		Return False
	;-- 收集所选颜色
	l_Color:=NumGet(CHOOSECOLOR,(A_PtrSize=8) ? 24:12,"UInt")
	;-- 转换为RGB
	l_Color:=((l_Color&0xFF)<<16)+(l_Color&0xFF00)+((l_Color>>16)&0xFF)
	;-- 用选定的颜色更新
	r_Color:=Format("0x{:06X}",l_Color)

	Return True
}

GetCursorColor(x:="",y:="",w:=1,h:=1){ ;取色
	static pt
	pt?"":(DllCall("GetModuleHandle","str","gdiplus","UPtr"),VarSetCapacity(i,A_PtrSize=8?24:16,0),i:=Chr(1)
		,DllCall("gdiplus\GdiplusStartup","UPtr*",pt,"UPtr",&i,"UPtr",0))
	,(x="")?GetCursorPos(x,y):""
	,d:=DllCall("CreateCompatibleDC","Uint",0),VarSetCapacity(b,40,0),NumPut(w,b,4,"uint")
	,NumPut(h,b,8,"uint"),NumPut(40,b,0,"uint"),NumPut(1,b,12,"ushort"),NumPut(0,b,16,"uInt"),NumPut(32,b,14,"ushort")
	,m:=DllCall("CreateDIBSection","UPtr",d,"UPtr",&b,"uint",0,"UPtr*",0,"UPtr",0,"uint",0,"UPtr")
	,o:=DllCall("SelectObject","UPtr",d,"UPtr",m)
	,DllCall("BitBlt","UPtr",d,"int",0,"int",0,"int",w,"int",h,"UPtr",i:=DllCall("GetDC","UPtr",0),"int",x,"int",y,"uint",0x00CC0020)
	,DllCall("ReleaseDC","UPtr",0,"UPtr",i)
	,DllCall("gdiplus\GdipCreateBitmapFromHBITMAP","UPtr",m,"UPtr",Palette,"UPtr*",p)
	,DllCall("SelectObject","UPtr",d,"UPtr",o),DllCall("DeleteObject","UPtr",m)
	,DllCall("DeleteDC","UPtr",i),DllCall("DeleteDC","UPtr",d),VarSetCapacity(t,16)
	,NumPut(0,t,0,"uint"),NumPut(0,t,4,"uint"),NumPut(w,t,8,"uint"),NumPut(h,t,12,"uint")
	,VarSetCapacity(b,16+2*A_PtrSize,0),DllCall("Gdiplus\GdipBitmapLockBits","UPtr",p,"UPtr",&t,"uint",3,"int",0x26200a,"UPtr",&b)
	,e:= NumGet(b,8,"Int"),u:=NumGet(b,16,"UPtr"),r:=A_FormatInteger
	SetFormat,IntegerFast,hex
	if (w>1 or h>1)
	{
		f:=[]
		Loop,%h%
		{
			f[A_Index]:=j:=[],s:=(A_Index-1)*e
			Loop,%w%
				j[A_Index]:=NumGet(u+0,((A_Index-1)*4)+s,"UInt")  & 0x00ffffff ""
		}
	}
	else f:=NumGet(u+0,0,"UInt") & 0x00ffffff  ""
	SetFormat,IntegerFast,%r%
	DllCall("Gdiplus\GdipBitmapUnlockBits","UPtr",p,"UPtr",0)
	DllCall("gdiplus\GdipDisposeImage", "uint", p)
	return f
}

GetCursorPos(byref x,byref y){
	static i:=VarSetCapacity(i,8,0)
	DllCall("GetCursorPos","Ptr",&i),X:=NumGet(i,0,"Int"),y:=NumGet(i,4,"Int")
}

StringLower(InputVar, T = ""){
	StringLower, InputVar, InputVar, %T%
	return InputVar
}

EmptyMem(PID=""){
	pid:=!PID ? DllCall("GetCurrentProcessId") : pid
	h:=DllCall("OpenProcess", "UInt", 0x001F0FFF, "Int", 0, "Int", pid)
	DllCall("SetProcessWorkingSetSize", "UInt", h, "Int", -1, "Int", -1)
	DllCall("CloseHandle", "Int", h)
}

OpenAndSelect(sFullPath){
	SplitPath sFullPath, , sPath, ext, name_no_ext
	FolderPidl := DllCall("shell32\ILCreateFromPath", "Str", sPath)
	DllCall("shell32\SHParseDisplayName", "str", sFullPath, "Ptr", 0, "Ptr*", ItemPidl := 0, "Uint", 0, "Uint*", 0)
	DllCall("shell32\SHOpenFolderAndSelectItems", "Ptr", FolderPidl, "UInt", 1, "Ptr*", ItemPidl, "Int", 0)
	CoTaskMemFree(FolderPidl)
	if name_no_ext
		CoTaskMemFree(ItemPidl)
}

CoTaskMemFree(pv) {
	Return DllCall("ole32\CoTaskMemFree", "Ptr", pv)
}

/*
	FileDescription	文件描述说明
	FileVersion	文件版本
	InternalName	内部名称
	LegalCopyright	法律版权所有
	OriginalFilename	创建文件时所使用的名称
	ProductName	产品名称
	ProductVersion	产品版本
	CompanyName	企业名称
	PrivateBuild	私有版本的信息
	SpecialBuild	特殊内部版本信息
	LegalTrademarks	文件的商标和注册商标
*/
FileGetInfo(FilePath:="", p*) {   ; Written by SKAN, modified by HotKeyIt	; www.autohotkey.com/forum/viewtopic.php?p=233188#233188  CD:24-Nov-2008 / LM:27-Oct-2010
	static DLL:="Version\GetFileVersion"
	If ! FSz := DllCall( DLL "InfoSize" (A_IsUnicode ? "W" : "A"), "Str",FilePath, "UInt",0 )
		Return DllCall( "SetLastError", UInt,1 ),""
	VarSetCapacity( FVI, FSz, 0 ),DllCall( DLL "Info" ( A_IsUnicode ? "W" : "A"), "Str",FilePath, "UInt",0, "UInt",FSz, "PTR",&FVI )
	If !DllCall( "Version\VerQueryValue" (A_IsUnicode ? "W" : "A"), "PTR",&FVI, "Str","\VarFileInfo\Translation", "PTR*",Transl, "PTR",0 )
		Return DllCall( "SetLastError", UInt,2 ),""
	If !Trans:=format("{1:.8X}",NumGet(Transl+0,"UInt"))
		Return DllCall( "SetLastError", UInt,3),""
	for k,v in p
	{
		subBlock := "\StringFileInfo\" SubStr(Trans,-3) SubStr(Trans,1,4) "\" v
		If ! DllCall( "Version\VerQueryValue" ( A_IsUnicode ? "W" : "A"), "PTR",&FVI, "Str",SubBlock, "PTR*",InfoPtr, "UInt",0 )
			continue
		If Value := StrGet( InfoPtr )
			Info .= p.MaxIndex()=1?Value:SubStr( v "                        ",1,24 ) . A_Tab . Value . "`n"
	}
	Info:=RTrim(Info,"`n")

	Return Info
}

GetProcessInfo(exename,type:="ExecutablePath") {
	/*
	class Win32_Process : CIM_Process
	{
		string   CreationClassName;	创建类的名称
		string   Caption;	进程标题
		string   CommandLine;	进程的命令行
		datetime CreationDate;	创建日期
		string   CSCreationClassName;
		string   CSName;
		string   Description;	显示进程说明
		string   ExecutablePath;	可执行路径
		uint16   ExecutionState;	执行状态
		string   Handle;	句柄
		uint32   HandleCount;	句柄统计
		datetime InstallDate;	安装日期
		uint64   KernelModeTime;	内核调节时间
		uint32   MaximumWorkingSetSize;
		uint32   MinimumWorkingSetSize;
		string   Name;	进程名
		string   OSCreationClassName;	系统创建类名
		string   OSName;	系统名
		uint64   OtherOperationCount;
		uint64   OtherTransferCount;
		uint32   PageFaults;	页面默认值
		uint32   PageFileUsage;
		uint32   ParentProcessId;
		uint32   PeakPageFileUsage;
		uint64   PeakVirtualSize;
		uint32   PeakWorkingSetSize;
		uint32   Priority = NULL;
		uint64   PrivatePageCount;
		uint32   ProcessId;	进程ID
		uint32   QuotaNonPagedPoolUsage;
		uint32   QuotaPagedPoolUsage;
		uint32   QuotaPeakNonPagedPoolUsage;
		uint32   QuotaPeakPagedPoolUsage;
		uint64   ReadOperationCount;
		uint64   ReadTransferCount;
		uint32   SessionId;	会话的唯一标识符
		string   Status;	状态值
		datetime TerminationDate;	终止日期
		uint32   ThreadCount;	线程计数
		uint64   UserModeTime;	用户模式时间
		uint64   VirtualSize;	虚拟化大小
		string   WindowsVersion;
		uint64   WorkingSetSize;
		uint64   WriteOperationCount;
		uint64   WriteTransferCount;
	};
	*/
	for process in ComObjGet("winmgmts:").ExecQuery("Select * from Win32_Process where name ='" exename "'")
		return process[type]
}

/*
	判断exe文件是32位还是64位
	返回值包含字符解释：IA64是intel推出的架构，IA64不兼容原有的32位x86架构指令集
		AMD64是AMD推出的也叫 X64 指令集，对原有的32位X86架构进行了扩展，有良好的兼容性
		i386是32位指令集统称
*/
FileGetBits(vPath) {
	IMAGE_DOS_SIGNATURE := 0x5A4D
	IMAGE_NT_SIGNATURE := 0x4550
	Machines := {0x014c: "IMAGE_FILE_MACHINE_I386", 0x0200: "IMAGE_FILE_MACHINE_IA64", 0x8664: "IMAGE_FILE_MACHINE_AMD64"}
	if ((file := FileOpen(vPath, "r")))
	{
		if (file.ReadUShort() == IMAGE_DOS_SIGNATURE)
		{
			file.Seek(60)
			e_lfanew := file.ReadInt()
			file.Seek(e_lfanew)
			if (file.ReadUInt() == IMAGE_NT_SIGNATURE)
			{
				file.Seek(e_lfanew + 4)
				vOutput := Machines[file.ReadUShort()]
			}
		}
		file.Close()
	}

	return vOutput
}

ChangeWindowIcon(IconFile, hWnd:="", IconNumber:=1, IconSize:=128) {    ;ico图标文件IconNumber和IconSize不用填，如果是icl图标库需要填
	hWnd :=hWnd?hWnd:WinExist("A")
	if (!hWnd)
		return "窗口不存在！"
	if not IconFile~="\.ico$"
		hIcon := LoadIcon(IconFile, IconNumber, IconSize)
	else
		hIcon := DllCall("LoadImage", uint, 0, str, IconFile, uint, 1, int, 0, int, 0, uint, LR_LOADFROMFILE:=0x10)
	if (!hIcon)
		return "图标文件不存在！"
	SendMessage, WM_SETICON:=0x80, ICON_SMALL2:=0, hIcon,, ahk_id %hWnd%  ; Set the window's small icon
	;;;SendMessage, STM_SETICON:=0x0170, hIcon, 0,, Ahk_ID %hWnd%
	SendMessage, WM_SETICON:=0x80, ICON_BIG:=1   , hIcon,, ahk_id %hWnd%  ; Set the window's big icon to the same one.
}


;获取exe/dll/icl文件中指定图标找返回
LoadIcon(Filename, IconNumber, IconSize)
{
	if DllCall("PrivateExtractIcons"
		, "str", Filename, "int", IconNumber-1, "int", IconSize, "int", IconSize
		, "ptr*", hIcon, "uint*", 0, "uint", 1, "uint", 0, "ptr")
		return hIcon
}

GetProcessNameList(ProcessName:=""){
	list:="",tarr:=[]
	s := 10240  ; 缓存和数组的大小(4 KB)

	Process, Exist  ; 设置 ErrorLevel 为这个正在运行脚本的 PID.
	; 使用 PROCESS_QUERY_INFORMATION(0x0400) 获取此脚本的句柄:
	h := DllCall("OpenProcess", "UInt", 0x0400, "Int", false, "UInt", ErrorLevel, "Ptr")
	; 打开此进程的可调整的访问令牌(TOKEN_ADJUST_PRIVILEGES = 32):
	DllCall("Advapi32.dll\OpenProcessToken", "Ptr", h, "UInt", 32, "PtrP", t)
	VarSetCapacity(ti, 16, 0)  ; 特权结构
	NumPut(1, ti, 0, "UInt")  ; 特权数组中的一个条目...
	; 获取调试特权的本地唯一标识符:
	DllCall("Advapi32.dll\LookupPrivilegeValue", "Ptr", 0, "Str", "SeDebugPrivilege", "Int64P", luid)
	NumPut(luid, ti, 4, "Int64")
	NumPut(2, ti, 12, "UInt")  ; 启用这个特权: SE_PRIVILEGE_ENABLED = 2
	; 使用新的访问令牌更新此进程的特权:
	r := DllCall("Advapi32.dll\AdjustTokenPrivileges", "Ptr", t, "Int", false, "Ptr", &ti, "UInt", 0, "Ptr", 0, "Ptr", 0)
	DllCall("CloseHandle", "Ptr", t)  ; 关闭此访问令牌句柄以节约内存.
	DllCall("CloseHandle", "Ptr", h)  ; 关闭此进程句柄以节约内存.

	hModule := DllCall("LoadLibrary", "Str", "Psapi.dll")  ; 通过预加载来提升性能.
	s := VarSetCapacity(a, s)  ; 接收进程列表标识符的数组:

	DllCall("Psapi.dll\EnumProcesses", "Ptr", &a, "UInt", s, "UIntP", r)
	Loop, % r // 4  ; 把数组解析为 DWORD(32 位) 的标识符:
	{
		id := NumGet(a, A_Index * 4, "UInt")
		; 打开进程: PROCESS_VM_READ(0x0010) | PROCESS_QUERY_INFORMATION(0x0400)
		h := DllCall("OpenProcess", "UInt", 0x0010 | 0x0400, "Int", false, "UInt", id, "Ptr")
		if !h
			continue
		VarSetCapacity(n, s, 0)  ; 接收模块基础名称的缓存:
		e := DllCall("Psapi.dll\GetModuleBaseName", "Ptr", h, "Ptr", 0, "Str", n, "UInt", A_IsUnicode ? s//2 : s)
		if !e    ;  用于 64 位进程在 32 位模式时的回退方法:
			if e := DllCall("Psapi.dll\GetProcessImageFileName", "Ptr", h, "Str", n, "UInt", A_IsUnicode ? s//2 : s)
				SplitPath n, n
		DllCall("CloseHandle", "Ptr", h)  ; 关闭进程句柄以节约内存
		if (n && e){  ; 如果映像不是空的, 则添加到列表:
			If (ProcessName&&ProcessName=n)
				tarr.push([n,id])
			else
				list.=n "/" id "|"
		}
	}
	DllCall("FreeLibrary", "Ptr", hModule)  ; 卸载库来释放内存.

	return !ProcessName?list:tarr
}
